require("dotenv").config({ path: ".env.dev" });
const path = require("path");
const Koa = require("koa");
const Router = require("koa-router");
const { Server } = require("socket.io");
const { createServer } = require("http");
const statics = require("koa-static");
const bodyParser = require("koa-bodyparser");
const cors = require("@koa/cors");
const { useJwt } = require("./utils/jwt");
const indexRouter = require("./router/index");

// 创建koa对象
const app = new Koa();
// 创建路由对象
const router = new Router();
// 创建服务器对象，并传入koa实例的回调函数
const server = createServer(app.callback());
// 创建socket.io对象，并传入服务器对象
const io = new Server(server, {
  path: "/ws",
  cors: {
    origin: "http://localhost:63342",
  },
});

router.use(indexRouter.routes());

// 注册静态资源托管中间件（页面访问时不用带上assets）
app.use(statics(path.join(__dirname, "assets")));
// 注册请求体解析中间件
app.use(bodyParser());
// 注册跨域中间件
app.use(cors());
// 注册路由中间件
app.use(router.routes());

// 监听connection连接事件（客户端连接socket服务器时触发）
io.on("connection", (socket) => {
  // socket对象为WebSocket连接对象
  socket.send("服务器：连接成功！");
  // 获取当前socket服务器连接集合的连接数
  console.log("连接数：", io.sockets.sockets.size);

  // 遍历当前socket服务器连接集合
  io.sockets.sockets.forEach((item) => {
    item.send("广播消息：有新连接！");
  });

  // 验证token
  if (socket.handshake.headers?.authorization) {
    const verify = useJwt.verify(socket.handshake.headers?.authorization);
    if (!verify) {
      socket.send("token验证失败！");
      socket.disconnect();
      return;
    }
  }

  socket.on("message", (msg) => {
    console.log(msg);
    socket.send("服务器：收到！");

    socket.emit("myEvent", { data: "自定义事件" });

    if (msg?.close) {
      socket.disconnect();
    }
  });

  socket.on("anything", (msg) => {
    console.log("anything", msg);
  });

  socket.on("error", (e) => {
    console.log("error", e);
  });

  socket.on("disconnecting", () => {
    console.log("disconnecting", socket.connected);
  });

  socket.on("disconnect", () => {
    console.log("disconnect", socket.connected);
  });
});

// 启动服务器（回调函数可选）
server.listen(1085, () => {
  console.log("Server is running at http://localhost:1085");
});
